import axios from 'axios'
import { useUserStore } from '@/stores/user'
const userStore = useUserStore()

if(process.env.NODE_ENV === 'development') {
  axios.defaults.baseURL = 'http://localhost:3000'
}

axios.defaults.timeout = 60000

axios.defaults.withCredentials = true

// 请求拦截器
axios.interceptors.request.use(config => {
  //可以在请求头中添加token等

  let token = userStore.token
  if(token) {
    config.headers.Authorization = `Bearer ${token}`
  }

  return config
}, error => {
  // 请求错误
  console.log('请求错误:', error)
  return Promise.reject(error)
})


//响应拦截器
axios.interceptors.response.use(response => {
  // 响应成功
  console.log('响应成功:', response)
  const res = response.data
  if(res.data.code == 200) {
    return res.data
  } else {
    return Promise.reject({
      message: res.data.message || '请求失败',
      code: res.data.code || 500
    })
  }
}, error => {
  // 响应错误
  console.log('响应错误:', error)
  return Promise.reject(error)
})


export default axios;


